#include "httpmgr.h"

#include <QNetworkReply>



HttpMgr::~HttpMgr()
{

}

HttpMgr::HttpMgr()
{
}

void HttpMgr::PostHttpReq(QUrl &&url, QByteArray &&data, ReqID id, Modules mod)
{
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.length()));

    auto _this = shared_from_this();//用来生产一个this的共享指针std::shared_ptr<HttpMgr>

    QNetworkReply *reply = manager.post(request, data);
    connect(reply, &QNetworkReply::finished, [_this, reply, id, mod](){
        int err = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        // if (reply->error() != QNetworkReply::NoError){
        //     qDebug("http发送错误");
        //     reply->deleteLater();
        //     return;
        // }

        _this->HttpFinish(id, reply->readAll(), mod, static_cast<ErrorCodes>(err));
        reply->deleteLater();
    });
}

void HttpMgr::HttpFinish(ReqID id, QByteArray res, Modules mod, ErrorCodes err)
{
    switch(mod){

    case Modules::REGISTERMO_LOGIN:
        emit sig_reg_login_mod_finish(res, id, err);
        break;
    case Modules::Find_USER:
        emit sig_find_mod_finish(res, id, err);
        break;
    }
}
